<?php

require "../utility.php";
require "./ac_utility.php";

function updateAddrToDatabase(mysqli $conn, string $user_id, string $addr, string $id, string $is_default): bool {
    $is_default_bool = boolval($is_default);

    if ($is_default_bool) {
        // 保持唯一性
        if (!keepUnique($conn, $user_id)) {
            return false;
        }
    }

    $update_str = "UPDATE Addr SET address = ?, isDefault = ? WHERE ID = ?;";
    $update_stmt = $conn->prepare($update_str);
    $update_stmt->bind_param("sii", $addr, $is_default_bool, $id);
    $status = $update_stmt->execute();
    return $status;
}

$conn = connect_mysql();
$user_id = getUserIdBySessionId($conn);
$addr_json = getJsonDataFromRawInput();

http_response_code(403);

if ($user_id    !== null &&
    check_keys($addr_json, "id", "address", "default")) {
    
    $id = $addr_json["id"];
    $address = $addr_json["address"];
    $is_default = $addr_json["default"];
    if (updateAddrToDatabase($conn, $user_id, $address, $id, $is_default)) {
        http_response_code(200);
    }
}

$conn->close();

?>